# 构建阶段：使用基础镜像进行编译和安装
FROM python-base:3.12-slim AS builder

# 接收构建参数
ARG VERSION=0.1.0
ARG UV_DEFAULT_INDEX=https://mirrors.aliyun.com/pypi/simple

# 添加项目文件
ADD scorpio /opt/sufe/scorpio

USER root
# 确保文件权限正确, 初始化scorpio虚拟环境
RUN set -eux; \
    chown -R sufe:sufe /opt/sufe

USER sufe
# 设置为容器内部环境变量
ENV VERSION=${VERSION}
ENV UV_DEFAULT_INDEX=${UV_DEFAULT_INDEX}
ENV VENV_DIR=/opt/sufe/scorpio/.venv

# 定义wheel包文件名
ENV WHEEL_FILE=scorpio-${VERSION}-py3-none-any.whl

RUN set -eux; \
    cd /opt/sufe/scorpio && \
    uv venv --prompt scorpio && \
    . ${VENV_DIR}/bin/activate && \
    uv sync && \
    uv pip install --no-cache-dir build -i ${UV_DEFAULT_INDEX} && \
    python -m build

# 将wheel包复制到指定位置
RUN set -eux; \
    ls /opt/sufe/scorpio/dist && \
    cp /opt/sufe/scorpio/dist/${WHEEL_FILE} /opt/sufe/

# 安装scorpio wheel包到虚拟环境
RUN set -eux; \
    cd /opt/sufe/scorpio && \
    . ${VENV_DIR}/bin/activate && \
    uv pip install --no-cache-dir dist/${WHEEL_FILE} -i ${UV_DEFAULT_INDEX}

# 第二阶段：创建最终镜像
FROM python-base:3.12-slim AS final

# 接收构建参数
ARG VERSION=0.1.0

# 设置为容器内部环境变量
ENV VERSION=${VERSION}
ENV VENV_DIR=/opt/sufe/scorpio/.venv

ADD scripts/entrypoints/scorpio.sh /opt/scorpio.sh 
ADD scripts/entrypoints/mysql-mcp-server.sh /opt/mysql-mcp-server.sh
RUN set -eux; \
    mkdir  /opt/sufe/scorpio

# 从构建阶段复制必要的文件
# COPY --from=builder /opt/sufe/scorpio/src/static /opt/sufe/scorpio/src
COPY --from=builder /opt/sufe/scorpio/scorpio_config_sample.json /opt/sufe/scorpio/scorpio_config.json
COPY --from=builder /opt/sufe/scorpio/.venv /opt/sufe/scorpio/.venv
# 确保文件权限正确
#USER root
#RUN set -eux; \
#    chown -R sufe:sufe /opt/sufe /opt/scorpio.sh /opt/mysql-mcp-server.sh
#USER sufe
# 设置工作目录
WORKDIR /opt/sufe
